package com.zhc.dejingapi.utils.qing;


import com.google.gson.Gson;
import com.zhc.dejingapi.pojo.qingflow.QingflowApiInfo;
import com.zhc.dejingapi.pojo.qingflow.token.accessTokenMainModel;
import com.zhc.dejingapi.utils.HttpClientUtil;
import com.zhc.dejingapi.utils.common.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class accessTokenUtils {


    private static final Logger log = LoggerFactory.getLogger(accessTokenUtils.class);
    public static String _QingAccessToken = "";
    public static Date _QindExpireDate;

    private static RedisTemplate<String, Object> redisTemplate;


    @Resource
    public void setRedisTemplate(@Qualifier("redisTemplateWin") RedisTemplate<String, Object> redisTemplate1) {

        this.redisTemplate = redisTemplate1;

    }




    public static String getAccessToken(QingflowApiInfo qingflowApiInfo) throws Exception {
        boolean bNeedGet = false;

       String strTokenSouce=qingflowApiInfo.getTokenSource();
       if(strTokenSouce==null){
           strTokenSouce="";
       }
       if(strTokenSouce.toLowerCase().equals("redis")){

           if (_QingAccessToken == null || _QingAccessToken.isEmpty()) {
               bNeedGet = true;
           } else if (_QindExpireDate.compareTo(new Date()) <= 0) {
               bNeedGet = true;
           }
           if(bNeedGet){
               try{
                   if(!(redisTemplate==null)){
                       _QingAccessToken = (String) redisTemplate.opsForValue().get("QingAccessToken");

                       String strDate=(String) redisTemplate.opsForValue().get("QingAccessTknExpireDate");
                       if(strDate==null||strDate.isEmpty()){
                           _QindExpireDate=DateTimeUtils.AddSecond(new Date(),10);
                       }
                       else{
                           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                           _QindExpireDate=sdf.parse(strDate);
                       }

                   }

               }
               catch (Exception e){
                   e.printStackTrace();
                   throw  e;
               }
           }


           return _QingAccessToken;
       }

        if (_QingAccessToken == null || _QingAccessToken.isEmpty()) {
            bNeedGet = true;
        } else if (_QindExpireDate.compareTo(new Date()) <= 0) {
            bNeedGet = true;
        }


        if (bNeedGet) {
            // 获取当前时间
            Date currentTime = new Date();
            //重新获取token
            Map<String, String> mapHead = new HashMap<>();
            String strUrl = qingflowApiInfo.getServerUrl();
            strUrl += "openApi/accessToken";
            strUrl += "?wsId=" + qingflowApiInfo.getWsId();
            strUrl += "&&wsSecret=" + qingflowApiInfo.getWsSecret();
            String strBack = HttpClientUtil.doGet(strUrl, mapHead);
            if (strBack == null || strBack.isEmpty()) {

            } else {
                try {

                    //accessTokenMainModel accessTokenMainModel = com.alibaba.fastjson.JSON.parseObject(strBack, accessTokenMainModel.class);
                    Gson gson = new Gson();
                    accessTokenMainModel accessTokenMainModel = gson.fromJson(strBack, accessTokenMainModel.class);
                    if (accessTokenMainModel == null) {
                        System.out.println("获取token失败");
                        log.error("获取token失败");
                        throw new Exception("获取token失败,返回内容为空！");
                    } else if (accessTokenMainModel.getErrCode() != 0) {
                        log.error("获取token失败");
                        throw new Exception("获取token失败：" + accessTokenMainModel.getErrCode() + "-" + accessTokenMainModel.getErrMsg() + "！");
                    } else {
                        _QingAccessToken = accessTokenMainModel.getResult().getAccessToken();

                        //redisHelper.set("QingAccessToken", _QingAccessToken);

                        // 将当前时间转换为毫秒数
                        long currentTimeInMillis = currentTime.getTime();

                        //redisHelper.set("QingAccessToken", _QingAccessToken);

                        if(!(redisTemplate==null)){
                            //,
                            //accessTokenMainModel.getResult().getExpireTime()-100,
                            //TimeUnit.SECONDS
                            redisTemplate.opsForValue().set("QingAccessToken",
                                    _QingAccessToken);
                        }
                        // 计算新的时间（当前时间加300秒）
                        long newTimeInMillis = currentTimeInMillis + (accessTokenMainModel.getResult().getExpireTime() * 1000);

                        // 将新的时间转换为可读格式
                        _QindExpireDate = new Date(newTimeInMillis);
                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String newTimeFormatted = sdf.format(_QindExpireDate);
                        redisTemplate.opsForValue().set("QingAccessTknExpireDate",
                                newTimeFormatted);
                        // 输出新的时间
                        //System.out.println("新的时间：" + newTimeFormatted);

                        //https://blog.51cto.com/u_16175453/6814891

                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                    log.info("获取token失败"+e);
                    throw e;
                }
            }


        }


        return _QingAccessToken;

    }
}
